package com.lian.pet.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lian.pet.common.basic.enums.DataTypeEnum;
import com.lian.pet.common.cache.redis.service.RedisService;
import com.lian.pet.domain.dto.AddPetVaccinesDTO;
import com.lian.pet.domain.dto.QueryPetVaccinesDTO;
import com.lian.pet.domain.entity.PetVaccines;
import com.lian.pet.domain.vo.PetVaccinesVO;
import com.lian.pet.factory.ResponseBeanFactory;
import com.lian.pet.mapper.PetVaccinesMapper;
import com.lian.pet.service.PetVaccinesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PetVaccinesServiceImpl implements PetVaccinesService {
    private final PetVaccinesMapper petVaccinesMapper;
    private final RedisService redisService;

    @Override
    public void addPetVaccines(AddPetVaccinesDTO req, Integer petId) {
        PetVaccines petVaccines = ResponseBeanFactory.getPetVaccines(req, petId);
        petVaccinesMapper.insert(petVaccines);
        // 添加数据时 删除Cache数据
        redisService.delKey(DataTypeEnum.PETVACCINES.name());
        log.info("执行成功[新增宠物接种记录]");
    }

    @Override
    public List<PetVaccinesVO> queryPetVaccines(QueryPetVaccinesDTO req, Integer petId) {
        IPage<PetVaccines> page = new Page<>(req.getPageNum(), req.getPageSize());
        IPage<PetVaccines> iPage = petVaccinesMapper.selectPage(page, Wrappers.<PetVaccines>lambdaQuery()
                .eq(PetVaccines::getPetId, petId)
                .eq(req.getPetId() != null, PetVaccines::getPetId, req.getPetId()));
        List<PetVaccines> petVaccines = iPage.getRecords();
        if (petVaccines.isEmpty()) {
            return Collections.emptyList();
        }
        List<PetVaccinesVO> petVaccinesVOS = new ArrayList<>();
        petVaccines.forEach(petVaccine -> {
            PetVaccinesVO petVaccinesVO = PetVaccinesVO.fromPetVaccines(petVaccine);
            petVaccinesVOS.add(petVaccinesVO);
        });

        log.info("执行成功[查询宠物已接种疫苗列表]");
        return petVaccinesVOS;
    }

    @Override
    public PetVaccinesVO getPetVaccines(Integer id) {
        PetVaccines petVaccines = petVaccinesMapper.selectById(id);
        return PetVaccinesVO.fromPetVaccines(petVaccines);
    }

    @Override
    public void deletePetVaccines(Integer id) {
        petVaccinesMapper.deleteById(id);
    }
}
